package com.youxin.chat.basic.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.youxin.base.BaseResultCode;
import com.youxin.chat.basic.convert.SysFileConvert;
import com.youxin.chat.basic.dto.constant.FileTypeEnum;
import com.youxin.chat.basic.dto.file.FileDto;
import com.youxin.chat.basic.dto.file.SysFileDto;
import com.youxin.chat.basic.mapper.SysFileMapper;
import com.youxin.chat.basic.model.SysFile;
import com.youxin.chat.basic.service.SysConfigService;
import com.youxin.chat.basic.service.SysFileService;
import com.youxin.chat.basic.util.FileContext;
import com.youxin.common.config.YouxinCommonProperties;
import com.youxin.exception.SystemException;
import com.youxin.qiniu.QiniuUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SysFileServiceImpl extends ServiceImpl<SysFileMapper, SysFile> implements SysFileService {

    private static final Logger logger = LoggerFactory.getLogger(SysFileServiceImpl.class);

    @Resource
    private SysConfigService sysConfigService;

    @Resource
    private YouxinCommonProperties youxinCommonProperties;

    @Override
    public String add(FileDto fileDto, Integer type) throws SystemException {
        SysFile record = SysFileConvert.dtoToModel(fileDto, type);
        save(record);
        return record.getId();
    }

    @Override
    public String saveFile(MultipartFile file, Integer type, String userNo) {
        SysFile sysFile = new SysFile();
        String filePath = youxinCommonProperties.getFilePath();
        String relFilePath = FileTypeEnum.forType(type).getPath();
        String fileId = FileContext.primaryId("F");
        String suffix = FileContext.getFileNameSuffix(file.getOriginalFilename());
        filePath += relFilePath;
        try {
            byte[] bytes = file.getBytes();
            QiniuUtil.upload(bytes, fileId);
        } catch (Exception e) {
            logger.error("创建文件失败", e);
            throw new SystemException(BaseResultCode.INTERNAL_ERROR, "文件上传失败");
        }
        sysFile.setId(fileId);
        sysFile.setSuffix(suffix);
        sysFile.setFilePath(relFilePath);
        sysFile.setFileSize(file.getSize());
        sysFile.setFileName(file.getOriginalFilename());
        sysFile.setCreateBy(userNo);
        save(sysFile);
        return fileId;
    }

    @Override
    public String saveFile(String parentPath, String fileName, InputStream inputStream) throws SystemException {
        String absoultePath = parentPath + "/" + fileName;
        File file = new File(absoultePath);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        if (file.exists()) {
            file.delete();
        }
        try {
            FileContext.writeFile(inputStream, absoultePath);
        } catch (Exception e) {
            logger.error("创建文件失败", e);
            throw new SystemException(BaseResultCode.INTERNAL_ERROR, "文件上传失败");
        }
        return absoultePath;
    }

    @Override
    public String getFileUrl() throws SystemException {

        return youxinCommonProperties.getDownloadUrl();

    }


    @Override
    public List<SysFileDto> getFilesByIds(List<String> fileIds) {
        List<SysFile> list = list(new LambdaQueryWrapper<SysFile>().in(SysFile::getId, fileIds));
        return list.stream().map(SysFileConvert::modelToDto).collect(Collectors.toList());
    }

    @Override
    public String saveFile(SysFileDto sysFileDto) {
        SysFile sysFile = SysFileConvert.dtoToModel(sysFileDto);
        save(sysFile);
        return sysFile.getId();
    }

    @Override
    public String getImageUrl(Integer type, String fileId) {
        return getFileUrl() + fileId;
    }

    @Override
    public String primaryId(String prefix) {
        return FileContext.primaryId(prefix);
    }

    @Override
    public FileDto download(String fileId) throws SystemException {
        FileDto fileDto = new FileDto();
        if (fileId == null || StringUtils.isEmpty(fileId)) {
            throw new SystemException(BaseResultCode.INTERNAL_ERROR, "文件ID不能为空");
        }

        SysFile resFileVo = getById(fileId);

        if (resFileVo == null) {
            throw new SystemException(BaseResultCode.INTERNAL_ERROR, "文件不存在");
        }

        String filePath = youxinCommonProperties.getFilePath();
        filePath += resFileVo.getFilePath() + resFileVo.getId() + resFileVo.getSuffix();

        logger.debug("FileServiceImpl:query 文件地址:{}", filePath);
        String fileName = resFileVo.getFileName();
        if (resFileVo.getFileType() != null && resFileVo.getFileType() == 2) {
            fileName = "youxin_" + DateTimeFormatter.ofPattern("yyyyMMddHHmmss").format(LocalDateTime.now()) + ".apk";
        }
        fileDto.setFileName(fileName);
        fileDto.setType(resFileVo.getFileType());
        //  fileDto.setFile(new File(filePath));
        fileDto.setFilePath(filePath);

        return fileDto;
    }
}
